<?php
/**
 * Created by PhpStorm.
 * User: zoujianshuang
 * Date: 18-8-10
 * Time: 下午2:37
 */
namespace common\filters;

use common\controllers\HelpersTrait;
use Yii;
use yii\base\ActionFilter;

class WechatFilter extends ActionFilter
{
    use HelpersTrait;

    public function beforeAction($action)
    {
        $isWx = $this->fromWx();
//        if (!$isWx || Yii::$app->request->isAjax) {
//            return true;
//        }

        //将open_id存储在session的resourceOwnerId字段
        //获取方式为Yii::$app->session->get('resourceOwnerId');
        if (!Yii::$app->session->has('resourceOwnerId') || !Yii::$app->session->has('resourceOwnerNickName')) {
            $wechat = Yii::$app->wechat;
            $getGrantState = bin2hex(random_bytes(8));
            Yii::$app->session->set('getGrantState', $getGrantState);
            $callbackUrl = Yii::$app->request->hostInfo . '/wechat/callback?redirect=' . urlencode(Yii::$app->request->absoluteUrl);
            $url = $wechat->getOauth2AuthorizeUrl($callbackUrl, 'snsapi_userinfo', $getGrantState);

            return Yii::$app->controller->redirect($url);
        }

        return true;
    }
}